package com.taptech.doufu.util;

import android.os.Environment;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * Created by op0509 on 2016/7/11.
 */
public class FileUtil {
    private static FileUtil fileUtil;
    public static String path = Environment.getExternalStorageDirectory() + "/Doufu/novel";

    public static FileUtil getInstance(){
        if(fileUtil == null){
            fileUtil = new FileUtil();
        }
        return fileUtil;
    }

    //创建文件夹
    public void createDir() {
        File file = new File(path);
        if (!file.exists()) {
            try {
                //按照指定的路径创建文件夹
                file.mkdirs();
            } catch (Exception e) {
            }
        }
    }

    //创建文件
    public void createDir(String path) {
        File dir = new File(path);
        if (!dir.exists()) {
            try {
                //在指定的文件夹中创建文件
                dir.createNewFile();
            } catch (Exception e) {
            }
        }
    }

    // 删除文件夹或文件
    public void delete(File file){
        if (file.isFile()) {
            file.delete();
            return;
        }

        if(file.isDirectory()){
            File[] childFiles = file.listFiles();
            if (childFiles == null || childFiles.length == 0) {
                file.delete();
                return;
            }

            for (int i = 0; i < childFiles.length; i++) {
                delete(childFiles[i]);
            }
            file.delete();
        }
    }

    //向已创建的文件中写入数据
    public void print(String str, String path) {
        File file = new File(path);
        if(file.exists()){
            file.delete();
        }
        FileWriter fw = null;
        BufferedWriter bw = null;
        String datetime = "";
        try {
            fw = new FileWriter(path, true);//
            // 创建FileWriter对象，用来写入字符流
            bw = new BufferedWriter(fw); // 将缓冲对文件的输出
            String myreadline = str;

            bw.write(myreadline + "\n"); // 写入文件
            bw.newLine();
            bw.flush(); // 刷新该流的缓冲
            bw.close();
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
            try {
                bw.close();
                fw.close();
            } catch (IOException e1) {
            }
        }
    }
}
